home *** CD-ROM | disk | FTP | other *** search
/ Java Primer Plus / Java Primer Plus (Waite Group Proess)(1996).iso / java_Win / demo / Fractal / ContextLSystem.class (.txt) < prev    next >
Encoding:
Java Class File  |  1995-10-12  |  2.3 KB  |  70 lines

  1. import java.applet.Applet;
  2. import java.util.Vector;
  3.  
  4. class ContextLSystem {
  5.    String axiom;
  6.    Vector rules = new Vector();
  7.    int level;
  8.    StringBuffer currentPath;
  9.  
  10.    public ContextLSystem(Applet app) {
  11.       this.axiom = app.getParameter("axiom");
  12.       int var2 = 1;
  13.  
  14.       while(true) {
  15.          String pred = app.getParameter("pred" + var2);
  16.          String succ = app.getParameter("succ" + var2);
  17.          if (pred == null || succ == null) {
  18.             this.currentPath = new StringBuffer(this.axiom);
  19.             this.level = 0;
  20.             return;
  21.          }
  22.  
  23.          this.rules.addElement(new CLSRule(pred, succ, app.getParameter("lContext" + var2), app.getParameter("rContext" + var2)));
  24.          ++var2;
  25.       }
  26.    }
  27.  
  28.    public int getLevel() {
  29.       return this.level;
  30.    }
  31.  
  32.    public synchronized String getPath() {
  33.       return this.currentPath == null ? null : this.currentPath.toString();
  34.    }
  35.  
  36.    private synchronized void setPath(StringBuffer path) {
  37.       this.currentPath = path;
  38.       ++this.level;
  39.    }
  40.  
  41.    public void generate() {
  42.       StringBuffer newPath = new StringBuffer();
  43.       int pos = 0;
  44.  
  45.       while(pos < this.currentPath.length()) {
  46.          CLSRule rule = this.findRule(pos);
  47.          if (rule == null) {
  48.             newPath.append(this.currentPath.charAt(pos));
  49.             ++pos;
  50.          } else {
  51.             newPath.append(rule.succ);
  52.             pos += rule.pred.length();
  53.          }
  54.       }
  55.  
  56.       this.setPath(newPath);
  57.    }
  58.  
  59.    public CLSRule findRule(int pos) {
  60.       for(int i = 0; i < this.rules.size(); ++i) {
  61.          CLSRule rule = (CLSRule)this.rules.elementAt(i);
  62.          if (rule.matches(this.currentPath, pos)) {
  63.             return rule;
  64.          }
  65.       }
  66.  
  67.       return null;
  68.    }
  69. }
  70.